package com.example.myapplication.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.myapplication.api.BackendApiClient
import com.example.myapplication.api.MonitoringStatus
import com.example.myapplication.config.AppConfig
import com.example.myapplication.data.BackendStockRepository
import com.example.myapplication.data.IStockRepository
import com.example.myapplication.model.SignalType
import com.example.myapplication.model.Stock
import com.example.myapplication.model.StockPrice
import com.example.myapplication.model.TradingSignal
import com.example.myapplication.service.SignalRecordService
import kotlinx.coroutines.launch
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive

/**
 * 股票ViewModel
 * 使用后端 API，所有业务逻辑由后端处理
 * 
 * 【新架构】后端主动监控推送模式：
 * - 监控完全在后端服务器运行，不依赖app前台
 * - 后端发现买卖点时通过FCM推送给app
 * - App只负责接收推送和显示数据
 */
class StockViewModel(application: Application) : AndroidViewModel(application) {
    
    // 使用后端 API 客户端
    private val apiClient = BackendApiClient(application)
    private val repository: IStockRepository = BackendStockRepository(application)
    private val signalRecordService = SignalRecordService(application)
    
    private val _stocks = MutableLiveData<List<Stock>>()
    val stocks: LiveData<List<Stock>> = _stocks
    
    private val _stockPrices = MutableLiveData<List<StockPrice>>()
    val stockPrices: LiveData<List<StockPrice>> = _stockPrices
    
    private val _tradingSignal = MutableLiveData<TradingSignal?>()
    val tradingSignal: LiveData<TradingSignal?> = _tradingSignal
    
    private val _tradingPoints = MutableLiveData<List<com.example.myapplication.model.TradingPoint>>()
    val tradingPoints: LiveData<List<com.example.myapplication.model.TradingPoint>> = _tradingPoints
    
    private val _stockAnalysisList = MutableLiveData<List<com.example.myapplication.model.StockAnalysis>>()
    val stockAnalysisList: LiveData<List<com.example.myapplication.model.StockAnalysis>> = _stockAnalysisList
    
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error
    
    // 后端监控状态
    private val _backendMonitoringStatus = MutableLiveData<MonitoringStatus?>()
    val backendMonitoringStatus: LiveData<MonitoringStatus?> = _backendMonitoringStatus
    
    private val _isMonitoring = MutableLiveData<Boolean>(false)
    val isMonitoring: LiveData<Boolean> = _isMonitoring
    
    private val _lastUpdateTime = MutableLiveData<Long>()
    val lastUpdateTime: LiveData<Long> = _lastUpdateTime
    
    private val _monitoringStockCount = MutableLiveData<Int>(0)
    val monitoringStockCount: LiveData<Int> = _monitoringStockCount
    
    // 定期查询后端监控状态的Job
    private var statusCheckJob: Job? = null
    
    /**
     * 加载推荐买入的股票列表（后台推荐，按时间排序）
     * 同时自动记录所有推荐股票的买入/卖出信号到数据库，用于回测
     */
    fun loadPopularStocks() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                // 调用推荐买入API，获取后台推荐的股票
                val stocks = apiClient.getRecommendedBuyStocks()
                _stocks.value = stocks
                
                android.util.Log.d("StockViewModel", "💰 加载推荐买入股票: ${stocks.size}个")
                
                // 🎯 自动记录所有推荐股票的交易信号到数据库（用于回测）
                launch {
                    try {
                        android.util.Log.d("StockViewModel", "🔄 开始自动记录推荐股票的交易信号...")
                        val result = signalRecordService.recordAllRecommendedStocks()
                        
                        if (result.isSuccess) {
                            android.util.Log.d("StockViewModel", """
                                ✅ 交易信号记录完成
                                   总股票: ${result.totalStocks}
                                   买入记录: ${result.buySignalsRecorded}
                                   卖出记录: ${result.sellSignalsRecorded}
                                   重复跳过: ${result.duplicateSkipped}
                            """.trimIndent())
                        } else {
                            android.util.Log.w("StockViewModel", "⚠️ 记录交易信号出现问题: ${result.error}")
                        }
                    } catch (e: Exception) {
                        android.util.Log.e("StockViewModel", "❌ 自动记录交易信号失败", e)
                    }
                }
                
            } catch (e: Exception) {
                _error.value = "加载推荐股票失败: ${e.message}"
                android.util.Log.e("StockViewModel", "❌ 加载推荐股票失败", e)
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 刷新推荐买入股票列表（下拉刷新使用）
     */
    fun refreshPopularStocks() {
        loadPopularStocks()
    }
    
    /**
     * 加载股票详情和生成交易信号
     * 从后端 API 获取所有数据
     */
    fun loadStockDetail(symbol: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                // 从后端获取历史数据（90天，显示最新数据）
                val prices = apiClient.getStockHistory(symbol, 90)
                
                // 详细日志：查看数据范围
                if (prices.isNotEmpty()) {
                    val firstDate = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA)
                        .format(java.util.Date(prices.first().timestamp))
                    val lastDate = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA)
                        .format(java.util.Date(prices.last().timestamp))
                    android.util.Log.d("StockViewModel", "📊 收到价格数据: ${prices.size}条")
                    android.util.Log.d("StockViewModel", "📅 数据范围: $firstDate 到 $lastDate")
                    android.util.Log.d("StockViewModel", "📌 最后5条数据:")
                    prices.takeLast(5).forEachIndexed { index, price ->
                        val date = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.CHINA)
                            .format(java.util.Date(price.timestamp))
                        android.util.Log.d("StockViewModel", "  [$index] $date - ¥${price.close}")
                    }
                }
                
                _stockPrices.value = prices
                
                // 从后端获取交易信号
                val signal = apiClient.getTradingSignal(symbol)
                _tradingSignal.value = signal
                
                // 从后端获取历史买卖点
                val points = apiClient.getTradingPoints(symbol)
                _tradingPoints.value = points
                
            } catch (e: Exception) {
                _error.value = "加载股票详情失败: ${e.message}"
                _tradingSignal.value = null
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 搜索股票
     */
    fun searchStocks(query: String) {
        if (query.isEmpty()) {
            loadPopularStocks()
            return
        }
        
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                val results = repository.searchStocks(query)
                _stocks.value = results
                
            } catch (e: Exception) {
                _error.value = "搜索失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 分析100只优质股票，预测买卖点
     * 后端批量处理，前端只负责展示
     */
    fun analyze100Stocks() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                // 直接从后端获取批量分析结果
                val analysisList = apiClient.analyzeBatchStocks()
                _stockAnalysisList.value = analysisList
                _monitoringStockCount.value = analysisList.size
                
                android.util.Log.d("StockViewModel", "📊 分析完成: ${analysisList.size}只股票")
                
            } catch (e: Exception) {
                _error.value = "分析股票失败: ${e.message}"
                android.util.Log.e("StockViewModel", "❌ 分析股票失败", e)
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 启动后端监控服务
     * 【新架构】调用后端API启动监控，监控完全在服务器端运行
     * 后端会持续监控股票，发现买卖点时通过FCM推送给app
     */
    fun startMonitoring(intervalSeconds: Int = 30) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                android.util.Log.d("StockViewModel", "🚀 请求后端启动监控服务，间隔：${intervalSeconds}秒")
                
                // 调用后端API启动监控
                val success = apiClient.startBackendMonitoring(intervalSeconds)
                
                if (success) {
                    _isMonitoring.value = true
                    android.util.Log.d("StockViewModel", "✅ 后端监控服务已启动")
                    
                    // 获取初始数据
                    fetchAndAnalyzeStocks()
                    
                    // 启动状态查询（每分钟查询一次后端监控状态）
                    startStatusCheck()
                } else {
                    _error.value = "启动后端监控失败"
                    android.util.Log.e("StockViewModel", "❌ 启动后端监控失败")
                }
                
            } catch (e: Exception) {
                _error.value = "启动监控异常: ${e.message}"
                android.util.Log.e("StockViewModel", "❌ 启动监控异常", e)
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 停止后端监控服务
     */
    fun stopMonitoring() {
        viewModelScope.launch {
            try {
                android.util.Log.d("StockViewModel", "⏹️ 请求后端停止监控服务")
                
                val success = apiClient.stopBackendMonitoring()
                
                if (success) {
                    _isMonitoring.value = false
                    stopStatusCheck()
                    android.util.Log.d("StockViewModel", "✅ 后端监控服务已停止")
                } else {
                    _error.value = "停止后端监控失败"
                    android.util.Log.e("StockViewModel", "❌ 停止后端监控失败")
                }
                
            } catch (e: Exception) {
                _error.value = "停止监控异常: ${e.message}"
                android.util.Log.e("StockViewModel", "❌ 停止监控异常", e)
            }
        }
    }
    
    /**
     * 启动定期查询后端监控状态
     */
    private fun startStatusCheck() {
        stopStatusCheck()
        
        statusCheckJob = viewModelScope.launch {
            android.util.Log.d("StockViewModel", "🔍 开始定期查询后端监控状态")
            
            while (isActive) {
                delay(60_000L) // 每分钟查询一次
                
                if (isActive) {
                    try {
                        val status = apiClient.getMonitoringStatus()
                        
                        if (status != null) {
                            _backendMonitoringStatus.value = status
                            _isMonitoring.value = status.isActive
                            _monitoringStockCount.value = status.monitoringStockCount
                            _lastUpdateTime.value = status.lastUpdateTime
                            
                            android.util.Log.d("StockViewModel", 
                                "📊 后端监控状态: ${if (status.isActive) "运行中" else "已停止"}, " +
                                "监控${status.monitoringStockCount}只股票, " +
                                "注册设备${status.registeredDevices}个")
                        }
                    } catch (e: Exception) {
                        android.util.Log.e("StockViewModel", "❌ 查询监控状态失败", e)
                    }
                }
            }
        }
    }
    
    /**
     * 停止状态查询
     */
    private fun stopStatusCheck() {
        statusCheckJob?.cancel()
        statusCheckJob = null
    }
    
    /**
     * 获取并分析100只股票（手动刷新数据）
     */
    private suspend fun fetchAndAnalyzeStocks() {
        try {
            android.util.Log.d("StockViewModel", "🔄 正在获取股票数据...")
            
            // 从后端获取100只股票的最新分析结果
            val analysisList = apiClient.analyzeBatchStocks()
            _stockAnalysisList.value = analysisList
            _monitoringStockCount.value = analysisList.size
            _lastUpdateTime.value = System.currentTimeMillis()
            
            // 统计买卖信号
            val buySignals = analysisList.count { it.tradingSignal?.signalType == SignalType.BUY }
            val sellSignals = analysisList.count { it.tradingSignal?.signalType == SignalType.SELL }
            val holdSignals = analysisList.count { it.tradingSignal?.signalType == SignalType.HOLD }
            
            android.util.Log.d("StockViewModel", """
                ✅ 数据更新完成: ${analysisList.size}只股票
                📈 买入信号: $buySignals 个
                📉 卖出信号: $sellSignals 个
                ⏸️ 持有信号: $holdSignals 个
            """.trimIndent())
            
        } catch (e: Exception) {
            android.util.Log.e("StockViewModel", "❌ 获取股票数据失败", e)
        }
    }
    
    /**
     * 查询后端监控状态
     */
    fun checkMonitoringStatus() {
        viewModelScope.launch {
            try {
                val status = apiClient.getMonitoringStatus()
                
                if (status != null) {
                    _backendMonitoringStatus.value = status
                    _isMonitoring.value = status.isActive
                    _monitoringStockCount.value = status.monitoringStockCount
                    _lastUpdateTime.value = status.lastUpdateTime
                    
                    android.util.Log.d("StockViewModel", "✅ 监控状态已更新")
                }
            } catch (e: Exception) {
                _error.value = "查询监控状态失败: ${e.message}"
                android.util.Log.e("StockViewModel", "❌ 查询监控状态失败", e)
            }
        }
    }
    
    /**
     * 手动刷新监控数据
     */
    fun refreshMonitoringData() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                fetchAndAnalyzeStocks()
            } catch (e: Exception) {
                _error.value = "刷新失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    /**
     * 清除错误信息
     */
    fun clearError() {
        _error.value = null
    }
    
    /**
     * ViewModel销毁时清理资源
     * 注意：不停止后端监控服务，因为监控在服务器端持续运行
     */
    override fun onCleared() {
        super.onCleared()
        stopStatusCheck()
        android.util.Log.d("StockViewModel", "🛑 ViewModel销毁，清理本地资源（后端监控继续运行）")
    }
}

